<!--  -->
<template>
  <div class="update-photo">
    <van-nav-bar title="修改密码" right-text="完成" left-text="取消" 
      @click-left="$emit('close')" @click-right="onConfirm" />

    <div class="name-field-wrap">
      <van-form>
        <van-field label="原密码" v-model="oldpwd"  placeholder="请填写原密码"
          :rules="[{ required: true, message: '请输入密码', trigger: 'onBlur' }]" />
        <van-field label="新密码" v-model="newpwd"  placeholder="请填写新密码"
          :rules="[{ required: true, message: '请输入密码', trigger: 'onBlur' }]" />
        <van-field label="确认新密码" v-model="resetpwd"  placeholder="确认新密码"
          :rules="[{ required: true, message: '请输入密码', trigger: 'onBlur' }]" />
      </van-form>
    </div>
  </div>
 
</template>

<script>
import { updatePwd } from '@/api/user'

export default {
  name:'UpdatePhoto',
  components: {},
  props:{
    value:{
      type:String,
      require:true
    }
  },
  data() {
    return {
      oldpwd: '',
      newpwd: '',
      resetpwd: '',
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
   async onConfirm(value){
     this.$toast.loading({
       message:'保存中',
       forbidClick:true  //禁止背景点击
     })

      if (this.oldpwd == this.newpwd) {
        this.$toast.fail('不能与原密码相同');
        this.oldpwd = "";
        this.newpwd = "";
        this.resetpwd = "";
        return false;
      }
      if (this.newpwd != this.resetpwd) {
        this.$toast.fail('与新密码不一致，请重新输入');
        this.newpwd = "";
        this.resetpwd = "";
        return false;
      }

      if (!/^[a-zA-Z]\w{5,17}$/.test(this.newpwd)) {
        this.$toast.fail('请输入正确的密码格式 提示：以字母开头，长度在6~18之间，只能包含字母、数字和下划线' );
        this.newpwd = "";
        this.resetpwd = "";
        return false;
      }

      try {
        const { data } = await updatePwd({
          "new_password": this.newpwd,
          "password": this.oldpwd,
        })

        if (data.code != "200") {
          this.$toast.fail('修改失败！' + data.msg);
        } else {
          this.$toast.success('修改成功!');
          //更新成功->修改父组件->关闭弹出层
          this.$emit('close');
        }
      } catch (error) {
        if (error) {
          this.$toast.fail('修改失败!');
        }
      }    
    }
  }
}

</script>
<style lang='less' scoped>
.name-field-wrap{
  padding: 10px;
}
</style>